﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Repository;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Text.Json;
using System.Threading.Tasks;

namespace Cxuu.Service
{

    [UseDI(ServiceLifetime.Scoped)]
    public class ConfigService
    {
        private readonly ConfigRepository configDal;
        private readonly ICacheManager _cacheManager;
        private readonly string cacheKey;
        public ConfigService(ConfigRepository configRepository, ICacheManager cacheManager)
        {
            configDal = configRepository;
            _cacheManager = cacheManager;
            cacheKey = _cacheManager.CacheName() + "SiteConfig";
        }



        /// <summary>
        /// siteinfo键名当前列数据
        /// </summary>
        /// <returns></returns>
        public async Task<EditConfigSiteInfo> GetByNameAsync()
        {
            Config config = _cacheManager.Get<Config>(cacheKey);
            if (config == null)
            {
                config = await configDal.GetByNameAsync("siteinfo");
                _cacheManager.Set(cacheKey, config, TimeSpan.FromDays(31));
            }
            return JsonSerializer.Deserialize<EditConfigSiteInfo>(config.Data);
        }

        /// <summary>
        /// 根据键名更新当前列
        /// </summary>
        /// <param name="config"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task<int> UpdateByNameAsync(Config config, string name)
        {
            _cacheManager.RemoveCacheAsync(cacheKey);
            return await configDal.UpdateByNameAsync(config, name);
        }
    }
}
